package com.yyl.rbacs.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @BelongsProject: redis
 * @BelongsPackage: com.yyl.redis.config
 * @Author: Yuan_
 * @CreateTime: 2022-11-17  09:58
 * @Description:
 * @Version: 1.0
 */

@Configuration
public class RedisConfig {
    
    
    @Bean
    public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
    
        RedisTemplate redisTemplate = new RedisTemplate();
        
        
        //设置连接工厂
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        
        //设置key序列化器
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    
        redisTemplate.setKeySerializer(stringRedisSerializer);
        
        //设置hash的key序列化器
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        
        //设置String类型的value序列化器
    
        final ObjectMapper objectMapper = new ObjectMapper();
        // 开启json字符串自动类型推断，解决从Redis中取到的json为LinkedHashMap问题
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
    
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        
        //设置hash的value序列化器
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        
        return redisTemplate;
    
    }
    
}
